<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { useRouter } from 'vue-router'
import { Page, useVbenModal } from '@vben/common-ui'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getMaterialList, doMaterialDelete, doMaterialApproval, doMaterialAgainst } from '#/api/material'
import { getAdminList } from '#/api/common'
import { Button, message, Popconfirm, Upload, Image, Tag, Input } from 'ant-design-vue'
import { useDebounceFn } from '@vueuse/core'

import { Spin } from 'ant-design-vue'
import { useAccessStore } from '@vben/stores'
import ChangeLog from './modules/changeLog.vue'
import Form from './modules/form.vue'

import { AntPlusOutlined, AntDownloadOutlined, AntUploadOutlined, AntDeleteOutlined, AntCheckOutlined, AntCloseOutlined } from '@vben/icons'

interface RowType {
  [key: string]: any
}
const params = ref<any>({
  quick_search: '',
})

const accessStore = useAccessStore()
const router = useRouter()
const keyword = ref('')
// 获取选中的行数据
const selectedRows = ref<any>([])
// 文件列表
const fileList = ref<any[]>([])
// 上传组件引用
const uploadRef = ref()
const uploadRef2 = ref()

const customHeaders = {
  batoken: accessStore.accessToken ?? '',
  'X-Requested-With': 'XMLHttpRequest',
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.material_id) // 修正为 material_id
}

// 审核按钮判断
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted >= 1) // 修正为 posted 小写
})

// 反审按钮判断
const isDisabledAgainst = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted === 0) // 修正为 posted 小写
})

const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'material_id',
  order: 'desc',
}

// 获取审核状态选项
const getPostedOptions = () => {
  return [
    {
      color: 'success',
      label: '已审核',
      value: 1,
    },
    { color: 'error', label: '未审核', value: 0 },
  ]
}

const formOptions: VbenFormProps = {
  // fieldMappingTime: [['created_at', ['start', 'end']]],
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'material_code',
      label: '物料编号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'material_name',
      label: '物料名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'material_attr',
      label: '成份',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'created*realname',
      label: '创建人',
      operator: '=',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'posted',
      label: '审核状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已审核',
            value: 1,
          },
          {
            label: '未审核',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'material_id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },

  cellConfig: {
    height: 80,
  },
  rowStyle({ row, rowIndex }) {
    if (row.posted === 0) {
      return {
        color: 'red',
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 70, fixed: 'left' },
    {
      field: 'posted',
      width: 70,
      title: '审核状态',
      fixed: 'left',
      slots: { default: 'posted' },
    },
    {
      field: 'temp_imgs',
      width: 100,
      title: '图片',
      slots: { default: 'image' },
    },
    { field: 'material_code', width: 120, title: '物料编号', fixed: 'left' },
    { field: 'material_name', width: 150, title: '物料名称', fixed: 'left' },
    { field: 'material_attr', width: 120, title: '成份' },
    {
      field: 'material_info',
      width: 180,
      title: '属性',
      type: 'html',
      // slots: { default: 'materialInfo' },
    },
    {
      field: 'purchase_info',
      width: 180,
      title: '采购信息',
      type: 'html',
      // slots: { default: 'purchaseInfo' },
    },
    { field: 'price', width: 100, title: '价格' },
    { field: 'gap', width: 100, title: '损耗' },
    { field: 'no_use_rate', width: 120, title: '无用率' },
    { field: 'material_type', width: 100, title: '类型' },
    { field: 'created_at', width: 160, title: '创建时间', sortable: true },
    { field: 'created.realname', width: 120, title: '创建人' },
    { field: 'updated_at', width: 160, title: '更新时间', sortable: true },
    { field: 'updatedRealname', width: 120, title: '修改人', slots: { default: 'updatedRealname' } },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 200,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues()
        const res = await getMaterialList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'material_list',
  customConfig: {
    storage: true,
  },
}

// 处理新建操作
const handleCreate = () => {
  router.push('/backend/material/form')
}

const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({
    content: '删除',
    duration: 0,
    key: 'action_process_msg',
  })

  doMaterialDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核操作
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核',
    duration: 0,
    key: 'action_process_msg',
  })

  doMaterialApproval({ ids: getSelectionIds(), is_confirm_ware: 0 })
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审操作
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }

  const hideLoading = message.loading({
    content: '反审',
    duration: 0,
    key: 'action_process_msg',
  })

  doMaterialAgainst({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '反审成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 获取环境变量
const apiUrl = import.meta.env.VITE_GLOB_API_URL || ''

// 处理导入成功回调
const handleImportSuccess = (response: any, file: any, fileList: any[]) => {
  if (response.code === 1) {
    message.success(response.msg || '导入成功')
    // 清空文件列表
    try {
      uploadRef.value?.clearFiles()
      uploadRef2.value?.clearFiles()
    } catch (error) {}
    // 刷新表格数据
    gridApi.query()
  } else {
    message.error(response.msg || '导入失败')
  }
}

// 处理导入失败回调
const handleImportError = (error: any, file: any, fileList: any[]) => {
  message.error('导入失败: ' + (error.message || '未知错误'))
}

// 处理下载模板操作
const handleDownloadTemplate = () => {
  let downloadUrl
  if (apiUrl) {
    const baseUrl = apiUrl.endsWith('/') ? apiUrl.slice(0, -1) : apiUrl
    downloadUrl = `${baseUrl}/static/template/物料档案导入格式.xlsx`
  } else {
    downloadUrl = '/static/template/物料档案导入格式.xlsx'
  }
  window.location.href = downloadUrl
}

// 处理下载外发损耗模板操作
const handleDownloadLossTemplate = () => {
  let downloadUrl
  if (apiUrl) {
    const baseUrl = apiUrl.endsWith('/') ? apiUrl.slice(0, -1) : apiUrl
    downloadUrl = `${baseUrl}/static/template/外发损耗导入模版.xlsx`
  } else {
    downloadUrl = '/static/template/外发损耗导入模版.xlsx'
  }
  window.location.href = downloadUrl
}

// 处理变更记录操作
const handleViewChangeRecord = (row: any) => {
  ChangeLogModalApi.setData({
    info: row,
  }).open()
}
const fetchData = async () => {
  gridApi.reload()
}
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})

const debouncedReload = useDebounceFn(gridApi.reload, 1000)

const [ChangeLogModal, ChangeLogModalApi] = useVbenModal({
  connectedComponent: ChangeLog,
})

const handleFormModal = (row: any) => {
  FormModalApi.setData({
    info: row,
  }).open()
}

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleFormModal({})">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          title="确认删除"
          :disabled="isDisabledApproval"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledApproval">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm title="确认审核" :disabled="isDisabledApproval" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
            <AntCheckOutlined />
            审核
          </Button>
        </Popconfirm>
        <Popconfirm title="确认反审" :disabled="isDisabledAgainst" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
            <AntCloseOutlined />
            反审
          </Button>
        </Popconfirm>

        <Upload
          ref="uploadRef"
          :action="apiUrl + '/admin/material/importData'"
          :headers="customHeaders"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :file-list="fileList"
          :multiple="false"
          :accept="'.xlsx,.xls'"
          :show-upload-list="false"
        >
          <template #default>
            <Button type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75">
              <AntUploadOutlined />
              导入数据
            </Button>
          </template>
        </Upload>
        <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" @click="handleDownloadTemplate()">
          <AntDownloadOutlined />
          下载模板
        </Button>

        <Upload
          ref="uploadRef2"
          :action="apiUrl + '/admin/material/importData'"
          :headers="customHeaders"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :file-list="fileList"
          :multiple="false"
          :accept="'.xlsx,.xls'"
          :show-upload-list="false"
        >
          <template #default>
            <Button type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75">
              <AntUploadOutlined />
              导入外发损耗
            </Button>
          </template>
        </Upload>
        <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" @click="handleDownloadLossTemplate()">
          <AntDownloadOutlined />
          下载外发损耗模板
        </Button>
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="供应商、物料名称模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>

      <template #image="{ row }">
        <div v-if="row.temp_imgs && row.temp_imgs.length > 0">
          <Image :src="row.temp_imgs[0]" fit="fill" @click.stop />
        </div>
        <span v-else>无图片</span>
      </template>

      <template #materialInfo="{ row }">
        <div v-if="row.material_info">
          {{ row.material_info }}
        </div>
      </template>

      <template #purchaseInfo="{ row }">
        <div v-if="row.purchase_info">
          {{ row.purchase_info }}
        </div>
      </template>

      <template #updatedRealname="{ row }">
        <div>{{ row.created.realname }}</div>
      </template>

      <template #posted="{ row }">
        <tag v-if="row.posted > 0">已审核</tag>
        <tag v-else class="text-red-500">未审核</tag>
      </template>

      <template #operation="{ row }">
        <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" size="small" @click.stop="handleViewChangeRecord(row)">变更记录</Button>
        <Button class="mr-2" type="primary" size="small" @click.stop="handleFormModal(row)">编辑</Button>
      </template>
    </Grid>
    <ChangeLogModal />
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
